package com.neo.sk.collector

import akka.actor.{Actor, Props}
import com.neo.sk.common.{FinishFetchByTag, Launcher, SaveFinishTagUrl, UrlTask}
import com.neo.sk.models.{MovieFinishTag, MovieTag}
import com.neo.sk.util.http.{DoubanLogin, HttpClientUtil}
import org.apache.http.impl.client.CloseableHttpClient
import org.slf4j.LoggerFactory

/**
 * User: Huangshanqi
 * Date: 2015/7/13
 * Time: 11:28
 */
class FetchMovieUrlManager extends Actor{
  private val logger = LoggerFactory.getLogger(this.getClass)

  private val userClient: CloseableHttpClient = HttpClientUtil.getHttpClient(DoubanLogin.Mylogin(),200)
  val saveActor = context.actorOf(Props[SaveActor](new SaveActor), "SaveActor-" + System.currentTimeMillis())
  private final val fetchMovieUrlActorNumber = 2
  private val fetchMovieUrlActors = (0 until fetchMovieUrlActorNumber).map{
    i=>
      context.actorOf(Props[FetchMovieUrlListActor](new FetchMovieUrlListActor(userClient)), "FetchMovieUrlListActor-" + i + "-" + System.currentTimeMillis())
  }

  val allTags = MovieTag.getAllTagName.toSet
  val finishTags = MovieFinishTag.getAllFinishTagName.toSet
  val undoTags = allTags.diff(finishTags)
  val tagUrlList = undoTags.map{
    tag =>
      //http://www.douban.com/tag/1990s/movie?start=15&retry=1
      "http://www.douban.com/tag/"+tag+"/movie?start=0&retry=1"
  }.toList
  logger.info(">>>> allTags = " + allTags.size + " ,finishTags = " + finishTags.size + " ,undoTags = " + undoTags.size + " <<<<")

  private val totalTagNum = tagUrlList.length
  private var currentTagNum = 0

  override def receive: Receive = {
    case Launcher =>{
      logger.info("start fetch tagUrlList...........................")
      fetchMovieUrlActors.foreach{
        slave =>
          val currentTagUrl = tagUrlList(currentTagNum)
          logger.info(">" * 10 + currentTagUrl + "<" * 10)
          slave ! UrlTask(currentTagUrl)
          currentTagNum += 1
      }
    }
    case FinishFetchByTag(url) =>{
      val tagPattern = "(.*)/tag/(.*)/movie(.*)".r
      val tagPattern(_,tag,_) = url
      saveActor ! SaveFinishTagUrl(url,tag)
      logger.info("finish=> " + url)
      if(currentTagNum < totalTagNum){
        val currentTagUrl = tagUrlList(currentTagNum)
        logger.info(">" * 10 + currentTagUrl + "<" * 10)
        sender() ! UrlTask(currentTagUrl)
        currentTagNum += 1
      }else{
        logger.info("finish all Url list========================================")
      }
    }
    case unknow@_ => logger.info("unknow message: "+ unknow + "  in " + context.self.path.name + " from " + context.sender().path.name)
  }

}
